<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/6/6
 * Time: 21:26
 */
namespace App\Tools;

use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Cache;

/**
 * 阿利大于短信相关
 * Class Alidayu
 * @package app\common\lib
 */
class Alidayu
{
    const LOG_TPL = "alidayu:";
    /**
     * 静态变量保存全局的实例
     * @var null
     */
    private static $_instance = null;

    /**
     * 私有的构造方法
     */
    private function __construct() {}

    /**
     * 静态方法 单例模式统一入口
     */
    public static function getInstance()
    {
        if(is_null(self::$_instance))
        {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /**
     * 发送短信接口
     * 文档地址 https://help.aliyun.com/document_detail/55451.html?spm=a2c4g.11186623.6.563.lX0Upj
     * @param int $mobile   手机号
     * @return mixed    code = OK 表示完成
     */
    public function sendSms($mobile,$params,$code)
    {

        require_once __DIR__.'/../../vendor/aliyunsms/vendor/autoload.php';


        //获取短信配置
        $appkey = config('aliyun.dayu_appkey');
        $secretkey = config('aliyun.dayu_secretkey');
        $name = config('aliyun.dayu_name');
       

        Config::load();

        $templateParam = ['number'=>$params];
        $product = "Dysmsapi";
        $domain = "dysmsapi.aliyuncs.com";
        $region = "cn-hangzhou";

        try
        {
            $profile = DefaultProfile::getProfile($region, $appkey, $secretkey);
            DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
            $acsClient= new DefaultAcsClient($profile);
            
            $request = new SendSmsRequest();
            $request->setPhoneNumbers($mobile);
            $request->setSignName($name);
            $request->setTemplateCode($code);
            
            if($templateParam)
            {
                $request->setTemplateParam(json_encode($templateParam));
            }
            $acsResponse = $acsClient->getAcsResponse($request);

        }
        catch (\Exception $e)
        {
            return false;
        }
        // 发送成功
        if($acsResponse->Code == 'OK')
        {
            // 设置验证码 并设置失效时间600/s  10分钟  存入缓存redis中
             Cache::set($mobile, $params, config('aliyun.dayu_identify_time'));
            return true;
        }
        else
        {
            //Log::write(self::LOG_TPL. json_encode($acsResponse));
            \Log::info(json_encode($acsResponse));

        }
        return false;
    }

    /**
     * 根据手机号码查询验证码是否正常
     * @param int $phone
     * @return boolean
     */
    public function checkSmsIdentify($phone = 0)
    {
        if(!$phone) return false;

        return Cache::get($phone);
    }
}